<?php

/**
 * Database Model base class, provides functionality for accessing the database
 *
 * @author Highstrike (highstrike@gmail.com)
 * @package CargoClaims
 * @version 1.0.dev
 */
abstract class MVC_Model
{
	/**
	 * Collection of objects which might be used by this model ( Databases, Caches, File resources, etc. )
	 *
	 * @var array
	 */
	private $entities;

	/**
	 * Reads an access object stored in this model
	 *
	 * @param string $object_key
	 * @throws MVC_Exception
	 */
	public function &__get($object_key)
	{
		if(isset($this-> entities[$object_key]))
			return $this-> entities[$object_key];
		else
			throw new MVC_Exception("Attempting to use an object which does not exist in model ".get_class($this));
	}

	// --- Database storage related (MVC_Database) --- //

	/**
	 * Sets up this model to use a database link
	 *
	 * @param MVC_Database $link
	 * @param string $object_key Defaults to "db" for ease of usage ( since in most cases there will only be a single database )
	 * @throws MVC_Exception
	 */
	public function use_Database(MVC_Database &$link, $object_key = 'db')
	{
		if(isset($this-> entities[$object_key]))
			throw new MVC_Exception("Key {$object_key} already used in the model ".get_class($this));

		$this-> entities[$object_key] = &$link;
	}

	public function table_Name($alias, $as_alias = true)
	{
		if(!isset($this-> tab[$alias]))
			throw new MVC_Exception("Attempting to use an inexisting table alias: {$alias}");
		$name = $this-> tab[$alias];
		if($as_alias)
			return "`$name` AS $alias";
		else
			return "`$name`";
	}

	// --- Persistence data related (MVC_Persist) --- //

	/**
	 * Sets up this model to use a persistent data manager
	 *
	 * @param MVC_Persist $obj
	 * @param string $object_key Defaults to "ss" for ease of usage, aka "Session", as this is the most common data manager
	 * @throws MVC_Exception
	 */
	public function use_Persist(MVC_Persist &$obj, $object_key = 'ss')
	{
		if(isset($this-> entities[$object_key]))
			throw new MVC_Exception("Key {$object_key} already used in the model ".get_class($this));

		$this-> entities[$object_key] = &$obj;
	}

}